package com.atbun.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atbun.oss.service.FileService;
import com.atbun.oss.utils.OssConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Description :
 * @Author : mayp
 * @Date: 2020-05-04 23:17
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = OssConstantPropertiesUtil.END_POINT;
        String accessKeyId = OssConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = OssConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = OssConstantPropertiesUtil.BUCKET_NAME;


        try{
//            判断oss实例是否存在，如果存在则获取，不存在则建
            OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);

//            获取上传文件流
            InputStream inputStream = file.getInputStream();
//            获取文件名
            String fileName = file.getOriginalFilename();
//            生成随机的值 replaceAll表示把-替换成空
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
//            生成结果如：uidhsu98uhdui海景1.jpg
            fileName = uuid+fileName;
//            拼接日期
            String datePath = new DateTime().toString("yyyy/MM/dd");
//            生成结果如：2019/12/09uidhsu98uhdui海景1.jpg 注意：日期前面生成的是文件夹
            fileName = datePath+"/"+fileName;

//            调用oss实现上传
            ossClient.putObject(bucketName,fileName,inputStream);

//            关闭流
            ossClient.shutdown();
//            上传之后把路径返回
            String uploadUrl = "https://"+bucketName+"."+endPoint+"/"+fileName;
            return uploadUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
